#-------------------------------------------------------------------------------
# Name:        Methods
# Purpose:
#
# Author:      Fedor
#
# Created:     28.11.2012
# Copyright:   (c) Fedor 2012
# Licence:     GPL
#-------------------------------------------------------------------------------
#!/usr/bin/env python
from settings import *
import os

class Hosting:
    vhost_nginx_path = os.path.join(HTTP_SERVER_PATH, u'sites-available')

    def create_django_project(self, projectName, hostName):
        djp = DjangoProject(projectName, hostName)
        djp.mkproject_dir()
        djp.mkvhost_nginx()

    def remove_django_project(self, projectName, hostName):
        djp = DjangoProject(projectName, hostName)
        djp.rmproject_dir()
        djp.rmvhost_nginx()

    def CountDjango(self):
        projects = os.listdir(ROOT_DJANGO_PROJECT_PATH)
        return len(projects)


class DjangoProject:
    projectName = None
    projectPath = None
    hostName = None
    vhost_nginx_path = os.path.join(HTTP_SERVER_PATH, u'sites-available')
    vhost_nginx_file_path = None

    def __init__(self, projectName, hostName):
        self.projectName = projectName
        self.hostName = hostName
        self.projectPath = os.path.join(ROOT_DJANGO_PROJECT_PATH, self.projectName)
        if not os.path.exists(self.vhost_nginx_path):
            os.makedirs(self.vhost_nginx_path)
        self.vhost_nginx_file_path = os.path.join(self.vhost_nginx_path, self.hostName)

    def mkproject_dir(self):
        if os.path.exists(self.projectPath):
            raise OSError(u"Directory: %s is exist" % self.projectPath)
        os.makedirs(self.projectPath)

    def rmproject_dir(self):
        if os.path.exists(self.projectPath):
            os.rmdir(self.projectPath)

    def mkvhost_nginx(self):
        if os.path.exists(self.vhost_nginx_file_path):
            raise IOError(u"File: %s is exist" % self.vhost_nginx_file_path)
        vhost_nginx_file = open(self.vhost_nginx_file_path, 'w')
        vhost_nginx_file.write(NGINX_DJANGO_VHOST_TMP)
        vhost_nginx_file.close()

    def rmvhost_nginx(self):
        if os.path.exists(self.vhost_nginx_file_path):
            os.remove(self.vhost_nginx_file_path)